import React, {
  useImperativeHandle,
  useState,
  forwardRef,
} from "react";
import { Button, Modal, Form, Input } from "antd";
import { addUser } from "../../../api/modules/user";
import {addRole} from "../../../api/modules/role";

const ModalCom = (props: any, ref: any) => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const { getList } = props;
  useImperativeHandle(ref, () => {
    return {
      showModal: showModal,
    };
  });
  type FieldType = {
    username?: string;
    password?: string;
  };
  const showModal = (record: any) => {
    if (record) {
      form.setFieldsValue(record);
    } else {
      form.resetFields();
    }
    setIsModalOpen(true);
  };

  const handleOk = () => {
    form
      .validateFields()
      .then(async (valid) => {
        const id = form.getFieldValue("id");
        const params = { ...valid, id };
        const result = await addRole(params);
        setIsModalOpen(false);
        getList();
      })
      .catch((err) => {
        return false;
      });
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  return (
    <>
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          form={form}
          name="basic"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item<FieldType> label="角色名称" name="name">
            <Input />
          </Form.Item>
          <Form.Item<FieldType> label="角色描述" name="description">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default forwardRef(ModalCom);
